package com.gdx.javatd;

import java.util.*;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;


public abstract class Turret extends Entity {
	
	private static Texture gunTexture;
	private Sprite gunSprite;
	
	private Monster target = null;
	private int range = 150;
	
	public Turret(int X, int Y) {
		super(X, Y);
		
		// Il faut charger les textures avant l'instanciation d'une tourelle
		gunSprite = new Sprite(gunTexture);
		gunSprite.setOrigin(16, 16);
	}
	
	public void step(ArrayList<Monster> monsters) {
		if ((target == null) || (target.distance(X, Y) > range)) {
			// Trouve un nouveau monstre cible
			target = findTarget(monsters);
		}
	}
	
	private Monster findTarget(ArrayList<Monster> monsters) {
		Monster closest = null;
		double minDistance = -1, distance;
		
		for (Monster mster : monsters) {
			distance = mster.distance(X, Y);
			if ((distance <= range) && (mster.isAlive())) {
				if ((closest == null) || (distance < minDistance)) {
					closest = mster;
					minDistance = distance;
				}
			}
		}
		
		return closest;
	}
	
	public void render(SpriteBatch batch) {
		batch.begin();
		baseSprite.setPosition(X, Y);
		baseSprite.draw(batch);
		gunSprite.setPosition(X, Y);
		if (target != null) gunSprite.setRotation((float) target.angle(X, Y));
		gunSprite.draw(batch);
		batch.end();
	}
	
	public static void setGunTexture(Texture gunTexture) {
		Turret.gunTexture = gunTexture;
		gunTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
	}
	
}
